<script lang="ts" setup>
import { User, Lock, Message, Position } from '@element-plus/icons-vue'
import { alertEffects, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive } from "@vue/reactivity";
import { ref } from "vue";

interface RuleForm {
    username: String,
    password: String,
    rePassword: String,
    email: String,
    phone: String,
}

const reg_password = /(^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{5,20}$)/
const reg_email = /(^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$)/
const reg_phone = /(^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$)/


const isRegister = ref(false)
const registerData = ref<RuleForm>({
    username: '',
    password: '',
    rePassword: '',
    email: '',
    phone: '',
})

const checkrepassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次确认密码'))
    } else if (value !== registerData.value.password) {
        callback(new Error('两次密码输入不一致，请再次输入'))
    } else {
        callback()
    }
}

import { useRouter } from 'vue-router'
const router = useRouter()

import { useToken } from '@/stores/token.js'
const usetoken = useToken()


import { getUserinfoServer } from '@/api/user.js'
import useUserInfo from '@/stores/userinfo.js'

const useuserinfo = useUserInfo() as any;
const getUserinfo = async () => {
    let result = await getUserinfoServer();
    useuserinfo.setInfo(result.data);
}
import {  useRoute } from 'vue-router';
const route = useRoute()
import { registerServer } from '@/api/user.js'
const register = async () => {
    let result = await registerServer(registerData.value) as any;
    usetoken.setToken(result.data)
    ElMessage.success(result.message ? '注册失败' : '注册成功')
    router.push('/login')
}

import { loginServer } from '@/api/user.js'
const login = async () => {
    let result = await loginServer(registerData.value) as any;
    getUserinfo()
    const ruler = useuserinfo.info.ruler
    usetoken.setToken(result.data)
    ElMessage.success(result.message ? result.message : '登录成功')
    if (ruler === '管理员') {
        router.push('/manager')
    }
    if (ruler === '普通用户' || ruler === '作者') {
        router.push('/home')
    }
}

const cleardata = () => {
    registerData.value = {
        username: '',
        password: '',
        rePassword: '',
        email: '',
        phone: '',
    }
}


const rules = reactive<FormRules<RuleForm>>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 15, message: '用户名要求3到15位的非空字符串', trigger: 'blur' }
    ],

    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: reg_password, message: '密码要求5到20位的数字和字母的组合', trigger: 'blur' }
    ],

    rePassword: [
        { validator: checkrepassword, trigger: 'blur' }
    ],

    email: [
        { required: false, message: '请输入邮箱', trigger: 'blur' },
        { pattern: reg_email, message: '名称允许汉字、字母、数字，域名只允许英文域名', trigger: 'blur' }
    ],

    phone: [
        { required: false, message: '请输入手机号', trigger: 'blur' },
        { pattern: reg_phone, message: '请输入正确的手机号', trigger: 'blur' }
    ],



})


const findword = async () =>{

    router.push('/repassword')
    
}
/*<div>
    <img :src="captchaUrl" @click="refreshCaptcha" alt="验证码" />
                    <el-image style="width: 100px; height: 100px" :src="captchaUrl" :fit="'验证码'" />
                    <input type="text" v-model="captchaInput" placeholder="请输入验证码" />
                </div>*/

</script>

<template>
    <el-row class="login-page">
        <el-col :span="12" class="bg"></el-col>
        <el-col :span="6" :offset="3" class="form">
            <!-- 注册表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
                <el-form-item>
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item prop="rePassword">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请再次输入密码"
                        v-model="registerData.rePassword"></el-input>
                </el-form-item>
                <el-form-item prop="email">
                    <el-input :prefix-icon="Message" type="email" placeholder="请输入邮箱"
                        v-model="registerData.email"></el-input>
                </el-form-item>
                <el-form-item prop="phone">
                    <el-input :prefix-icon="Position" type="phone" placeholder="请输入手机号"
                        v-model="registerData.phone"></el-input>
                </el-form-item>
                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="register">
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false; cleardata()">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-else :model="registerData" >
                <el-form-item>
                    <h1>登录</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        
                        <el-link type="primary" :underline="false" @click="findword()">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = true; cleardata()">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<style scoped>
.demo-image__error .image-slot {
    font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
    font-size: 30px;
}
</style>

<style lang="scss" scoped>
/* 样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
        background: url('@/assets/logo.png') no-repeat 60% center / 240px auto,
            url('@/assets/login_bg.jpg') no-repeat center / cover;
        border-radius: 0 20px 20px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>